<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  

  
  <title>简单的蓝牙通信 | 海晨忆的博客</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  
  
  
  <meta name="description" content="&amp;emsp;&amp;emsp;之前公司做智能家居类型，其中做了一个智能衣柜项目，与衣柜通信就是用的蓝牙通信。一些操作一些简单的开关指令，蓝牙通信与socket是类似的。">
<meta property="og:type" content="article">
<meta property="og:title" content="简单的蓝牙通信">
<meta property="og:url" content="https://haichenyi.com/2018/03/05/简单的蓝牙通信/index.html">
<meta property="og:site_name" content="海晨忆的博客">
<meta property="og:description" content="&amp;emsp;&amp;emsp;之前公司做智能家居类型，其中做了一个智能衣柜项目，与衣柜通信就是用的蓝牙通信。一些操作一些简单的开关指令，蓝牙通信与socket是类似的。">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2018-03-06T12:59:29.265Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="简单的蓝牙通信">
<meta name="twitter:description" content="&amp;emsp;&amp;emsp;之前公司做智能家居类型，其中做了一个智能衣柜项目，与衣柜通信就是用的蓝牙通信。一些操作一些简单的开关指令，蓝牙通信与socket是类似的。">
  
    <link rel="alternate" href="/atom.xml" title="海晨忆的博客" type="application/atom+xml">
  
  
    <link rel="icon" href="/uploads/artistic_image/head.jpg">
  
  
    <link href="//fonts.googleapis.com/css?family=Source+Code+Pro" rel="stylesheet" type="text/css">
  
  <link rel="stylesheet" href="/css/style.css">
  <link rel="stylesheet" href="/css/highlight.css">
  <script>
  let antiquityStorage = window.sessionStorage.getItem('antiquitySessionStorage');
  if (antiquityStorage == '' || antiquityStorage == null) {
    var antiquityLoader = '<div id="loaderbox"><div class="loader"><div class="load-roll"><div class="load-top"></div><div class="load-right"></div><div class="load-bottom"></div></div></div></div>';
    document.write(antiquityLoader);
    document.body.style.overflow = 'hidden'
  }
  </script>
</head>

<body>
  <div id="fullpage" class="mobile-nav-right">
    
      <div id="wrapper" style="background-image: url(/uploads/artistic_image/bg.jpg)" title="背景图片来自网络">
    
    
      <header id="header">
  <div id="nav-toggle" class="nav-toggle"></div>
  <div class="head-box global-width">
    <nav class="nav-box nav-right">
      
        <a class="nav-item" href="/" title
        
        >首页</a>
      
        <a class="nav-item" href="/archives" title
        
        >归档</a>
      
        <a class="nav-item" href="/about" title
        
        >简历</a>
      
    </nav>
  </div>
</header>
      <div id="middlecontent" title class="global-width sidebar-left">
        <section id="main"><article id="post-简单的蓝牙通信" class="article global-container article-type-post" itemscope itemprop="blogPost">
  
    <header class="article-header">
      
  
    <h1 class="article-title" itemprop="name">
      简单的蓝牙通信
    </h1>
  

    </header>
  
  <div class="article-meta">
    <a href="/2018/03/05/简单的蓝牙通信/" class="article-date">
  <time datetime="2018-03-05T12:12:58.000Z" itemprop="datePublished">2018-03-05</time>
</a>
    
  <div class="article-category">
    <a class="article-category-link" href="/categories/Android-常用功能/">Android -常用功能</a>
  </div>

    
  </div>
  
    <span id="busuanzi_container_page_pv">
      本文总阅读量<span id="busuanzi_value_page_pv"></span>次
    </span>
  

  <div class="article-inner">
    
    <div class="article-content article-content-cloud doorframe mac" itemprop="articleBody">
      
        <p>&emsp;&emsp;之前公司做智能家居类型，其中做了一个智能衣柜项目，与衣柜通信就是用的蓝牙通信。一些操作一些简单的开关指令，蓝牙通信与socket是类似的。</p>
<a id="more"></a>
<h3 id="步骤"><a href="#步骤" class="headerlink" title="步骤"></a>步骤</h3><ol>
<li>清单文件注册权限</li>
<li>启动蓝牙服务（记得在清单文件中静态注册服务）</li>
<li>注册蓝牙广播（在蓝牙服务中动态注册蓝牙广播）</li>
<li>搜索，绑定，完成</li>
<li>退出app，停止服务，并在蓝牙服务的onDestory方法中取消注册蓝牙广播</li>
</ol>
<p>不想写说明，只想贴代码</p>
<h4 id="第一步：注册权限"><a href="#第一步：注册权限" class="headerlink" title="第一步：注册权限"></a>第一步：注册权限</h4><div class="highlight-box"autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" contenteditable="true"data-rel="PLAIN"><figure class="iseeu highlight /plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">&lt;!--获取蓝牙信息状态权限--&gt;</span><br><span class="line">&lt;uses-permission android:name=&quot;android.permission.BLUETOOTH&quot;/&gt;</span><br><span class="line">&lt;uses-permission android:name=&quot;android.permission.BLUETOOTH_ADMIN&quot;/&gt;</span><br></pre></td></tr></table></figure></div>
<h3 id="第二步、第三步、第五步：启动蓝牙服务，注册蓝牙广播，停止服务"><a href="#第二步、第三步、第五步：启动蓝牙服务，注册蓝牙广播，停止服务" class="headerlink" title="第二步、第三步、第五步：启动蓝牙服务，注册蓝牙广播，停止服务"></a>第二步、第三步、第五步：启动蓝牙服务，注册蓝牙广播，停止服务</h3><div class="highlight-box"autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" contenteditable="true"data-rel="PLAIN"><figure class="iseeu highlight /plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">/**</span><br><span class="line"> * Author: 海晨忆.</span><br><span class="line"> * Date: 2018/1/4</span><br><span class="line"> * Desc:</span><br><span class="line"> */</span><br><span class="line">public class BluetoothService extends Service &#123;</span><br><span class="line">  //得到蓝牙适配器</span><br><span class="line">  private BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();</span><br><span class="line">  private BluetoothReceiver mReceiver;</span><br><span class="line"></span><br><span class="line">  @Override</span><br><span class="line">  public void onCreate() &#123;</span><br><span class="line">    super.onCreate();</span><br><span class="line">    EventBus.getDefault().register(this);</span><br><span class="line">    if (mBluetoothAdapter != null) &#123;</span><br><span class="line">      mReceiver = new BluetoothReceiver().setBluetoothAdapter(mBluetoothAdapter);</span><br><span class="line">      //注册设备被发现时的广播</span><br><span class="line">      IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);</span><br><span class="line">      registerReceiver(mReceiver, filter);</span><br><span class="line">      //注册一个搜索结束时的广播</span><br><span class="line">      IntentFilter filter2 = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);</span><br><span class="line">      registerReceiver(mReceiver, filter2);</span><br><span class="line">      startLinkBluetooth();</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  @Nullable</span><br><span class="line">  @Override</span><br><span class="line">  public IBinder onBind(Intent intent) &#123;</span><br><span class="line">    return null;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  /**</span><br><span class="line">   * 开始连接蓝牙设备.</span><br><span class="line">   */</span><br><span class="line">  private void startLinkBluetooth() &#123;</span><br><span class="line">    if (null != mBluetoothAdapter) &#123;</span><br><span class="line">      //判断蓝牙是否打开</span><br><span class="line">      if (!mBluetoothAdapter.isEnabled()) &#123;</span><br><span class="line">        //若没打开则打开蓝牙</span><br><span class="line">        mBluetoothAdapter.enable();</span><br><span class="line">      &#125;</span><br><span class="line">      mBluetoothAdapter.startDiscovery();</span><br><span class="line">      Log.v(Constants.HTTP_WZ, &quot;正在扫描&quot;);</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  @Subscribe</span><br><span class="line">  @SuppressWarnings(&quot;unused&quot;)</span><br><span class="line">  public void handleMsg(BluetoothInfo bluetoothInfo) &#123;</span><br><span class="line">    if (bluetoothInfo.isLink) &#123;</span><br><span class="line">      startLinkBluetooth();</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  public static class BluetoothInfo &#123;</span><br><span class="line">    private boolean isLink = false;</span><br><span class="line"></span><br><span class="line">    public BluetoothInfo setLink(boolean link) &#123;</span><br><span class="line">      this.isLink = link;</span><br><span class="line">      return this;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  @Override</span><br><span class="line">  public void onDestroy() &#123;</span><br><span class="line">    super.onDestroy();</span><br><span class="line">    EventBus.getDefault().unregister(this);</span><br><span class="line">    if (mReceiver != null) &#123;</span><br><span class="line">      mReceiver.unRegister();</span><br><span class="line">      unregisterReceiver(mReceiver);</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<p>这个就是我的蓝牙服务类，这个类的逻辑怎么走的呢？</p>
<ol>
<li><p>EventBus的东西我就不说了</p>
</li>
<li><p>首先获取蓝牙适配器</p>
</li>
</ol>
<div class="highlight-box"autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" contenteditable="true"data-rel="PLAIN"><figure class="iseeu highlight /plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();</span><br></pre></td></tr></table></figure></div>
<ol>
<li>初始化蓝牙广播，注册蓝牙广播</li>
</ol>
<div class="highlight-box"autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" contenteditable="true"data-rel="PLAIN"><figure class="iseeu highlight /plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">if (mBluetoothAdapter != null) &#123;</span><br><span class="line">      mReceiver = new BluetoothReceiver().setBluetoothAdapter(mBluetoothAdapter);</span><br><span class="line">      //注册设备被发现时的广播</span><br><span class="line">      IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);</span><br><span class="line">      registerReceiver(mReceiver, filter);</span><br><span class="line">      //注册一个搜索结束时的广播</span><br><span class="line">      IntentFilter filter2 = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);</span><br><span class="line">      registerReceiver(mReceiver, filter2);</span><br><span class="line">      startLinkBluetooth();</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure></div>
<ol>
<li>开始准备连接蓝牙设备</li>
</ol>
<div class="highlight-box"autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" contenteditable="true"data-rel="PLAIN"><figure class="iseeu highlight /plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line">   * 开始连接蓝牙设备.</span><br><span class="line">   */</span><br><span class="line">  private void startLinkBluetooth() &#123;</span><br><span class="line">    if (null != mBluetoothAdapter) &#123;</span><br><span class="line">      //判断蓝牙是否打开</span><br><span class="line">      if (!mBluetoothAdapter.isEnabled()) &#123;</span><br><span class="line">        //若没打开则打开蓝牙</span><br><span class="line">        mBluetoothAdapter.enable();</span><br><span class="line">      &#125;</span><br><span class="line">      mBluetoothAdapter.startDiscovery();</span><br><span class="line">      Log.v(Constants.HTTP_WZ, &quot;正在扫描&quot;);</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br></pre></td></tr></table></figure></div>
<ol>
<li>上面4步蓝牙扫描就完成了，这里我还要说的是，在服务的onDestory方法里面，记得停止服务</li>
</ol>
<div class="highlight-box"autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" contenteditable="true"data-rel="PLAIN"><figure class="iseeu highlight /plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">@Override</span><br><span class="line">  public void onDestroy() &#123;</span><br><span class="line">    super.onDestroy();</span><br><span class="line">    EventBus.getDefault().unregister(this);</span><br><span class="line">    if (mReceiver != null) &#123;</span><br><span class="line">      mReceiver.unRegister();</span><br><span class="line">      unregisterReceiver(mReceiver);</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br></pre></td></tr></table></figure></div>
<ol>
<li>再就是在清单文件里面静态注册蓝牙服务</li>
</ol>
<div class="highlight-box"autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" contenteditable="true"data-rel="PLAIN"><figure class="iseeu highlight /plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&lt;service android:name=&quot;.service.BluetoothService&quot;/&gt;</span><br></pre></td></tr></table></figure></div>
<ol>
<li>启动服务的方式，我用的是非绑定的方式，同样，记得停止服务。</li>
</ol>
<div class="highlight-box"autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" contenteditable="true"data-rel="PLAIN"><figure class="iseeu highlight /plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">Intent bluetoothService = new Intent(this, BluetoothService.class);</span><br><span class="line">startService(bluetoothService);//启动蓝牙服务</span><br></pre></td></tr></table></figure></div>
<div class="highlight-box"autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" contenteditable="true"data-rel="PLAIN"><figure class="iseeu highlight /plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">stopService(bluetoothService);</span><br></pre></td></tr></table></figure></div>
<div class="highlight-box"autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" contenteditable="true"data-rel="PLAIN"><figure class="iseeu highlight /plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">@Nullable</span><br><span class="line">  @Override</span><br><span class="line">  public IBinder onBind(Intent intent) &#123;</span><br><span class="line">  //非绑定方式，返回值为null</span><br><span class="line">    return null;</span><br><span class="line">  &#125;</span><br></pre></td></tr></table></figure></div>
<h3 id="第四步：搜索，绑定，完成搜索"><a href="#第四步：搜索，绑定，完成搜索" class="headerlink" title="第四步：搜索，绑定，完成搜索"></a>第四步：搜索，绑定，完成搜索</h3><div class="highlight-box"autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" contenteditable="true"data-rel="PLAIN"><figure class="iseeu highlight /plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">/**</span><br><span class="line"> * Author: 海晨忆.</span><br><span class="line"> * Date: 2018/1/4</span><br><span class="line"> * Desc: 蓝牙广播监听</span><br><span class="line"> */</span><br><span class="line">public class BluetoothReceiver extends BroadcastReceiver &#123;</span><br><span class="line">  //衣柜的蓝牙名称</span><br><span class="line">  private static final String WARDROBE_NAME = &quot;WARDROBE&quot;;</span><br><span class="line">  // 固定的UUID</span><br><span class="line">  private static final String SPP_UUID = &quot;00001101-0000-1000-8000-00805F9B34FB&quot;;</span><br><span class="line">  private BluetoothSocket bluetoothSocket;</span><br><span class="line">  private BluetoothAdapter bluetoothAdapter;</span><br><span class="line">  private InputStream mInputStream;</span><br><span class="line">  private OutputStream outputStream;</span><br><span class="line">  private boolean isRunning = false;</span><br><span class="line"></span><br><span class="line">  @Override</span><br><span class="line">  public void onReceive(Context context, Intent intent) &#123;</span><br><span class="line">    String action = intent.getAction();</span><br><span class="line">    if (action != null) &#123;</span><br><span class="line">      if (action.equals(BluetoothDevice.ACTION_FOUND)) &#123;</span><br><span class="line">        BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);</span><br><span class="line">        Log.v(Constants.HTTP_WZ, device.getName() + device.getAddress());</span><br><span class="line">        if (device.getBondState() == BluetoothDevice.BOND_BONDED</span><br><span class="line">            &amp;&amp; device.getName().equals(WARDROBE_NAME)) &#123;</span><br><span class="line">          UUID uuid = UUID.fromString(SPP_UUID);</span><br><span class="line">          try &#123;</span><br><span class="line">            bluetoothSocket = device.createRfcommSocketToServiceRecord(uuid);</span><br><span class="line">            Log.v(Constants.HTTP_WZ, &quot;准备连接&quot;);</span><br><span class="line">            connect();</span><br><span class="line">          &#125; catch (IOException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">          &#125;</span><br><span class="line">        &#125;</span><br><span class="line">      &#125; else if (action.equals(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)) &#123;</span><br><span class="line">        if (!EventBus.getDefault().isRegistered(this))</span><br><span class="line">          EventBus.getDefault().register(this);</span><br><span class="line">        Observable.timer(2, TimeUnit.SECONDS)</span><br><span class="line">            .observeOn(AndroidSchedulers.mainThread())</span><br><span class="line">            .subscribe(aLong -&gt; &#123;</span><br><span class="line">              if (null == bluetoothSocket || !bluetoothSocket.isConnected())</span><br><span class="line">                ToastUtils.showTipMsg(R.string.no_wardrobe);</span><br><span class="line">            &#125;);</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  private void connect() &#123;</span><br><span class="line">    new Thread(() -&gt; &#123;</span><br><span class="line">      if (bluetoothSocket != null) &#123;</span><br><span class="line">        bluetoothAdapter.cancelDiscovery();</span><br><span class="line">        try &#123;</span><br><span class="line">          bluetoothSocket.connect();</span><br><span class="line">          Observable.just(1)</span><br><span class="line">              .observeOn(AndroidSchedulers.mainThread())</span><br><span class="line">              .subscribe(integer -&gt; ToastUtils.showTipMsg(R.string.link_wardrobe));</span><br><span class="line">          Log.v(Constants.HTTP_WZ, &quot;连接成功&quot;);</span><br><span class="line">          mInputStream = bluetoothSocket.getInputStream();</span><br><span class="line">          Log.v(Constants.HTTP_WZ, &quot;mInputSream:&quot; + mInputStream.toString());</span><br><span class="line">          isRunning = true;</span><br><span class="line">          outputStream = bluetoothSocket.getOutputStream();</span><br><span class="line">          Log.v(Constants.HTTP_WZ, &quot;outputStream:&quot; + outputStream.toString());</span><br><span class="line">          BufferedReader br;</span><br><span class="line">          while (isRunning) &#123;</span><br><span class="line">            br = new BufferedReader(new InputStreamReader(mInputStream, &quot;utf-8&quot;));</span><br><span class="line">            String s = br.readLine();</span><br><span class="line">            //acceptReply(s);</span><br><span class="line">            Log.v(Constants.HTTP_WZ, &quot;收到的数据:&quot; + s);</span><br><span class="line">          &#125;</span><br><span class="line">        &#125; catch (IOException e) &#123;</span><br><span class="line">          e.printStackTrace();</span><br><span class="line">          try &#123;</span><br><span class="line">            if (mInputStream != null) &#123;</span><br><span class="line">              mInputStream.close();</span><br><span class="line">              Log.v(Constants.HTTP_WZ, &quot;mInputSream.close()&quot;);</span><br><span class="line">            &#125;</span><br><span class="line">            if (outputStream != null) &#123;</span><br><span class="line">              outputStream.close();</span><br><span class="line">              Log.v(Constants.HTTP_WZ, &quot;outputStream.close()&quot;);</span><br><span class="line">            &#125;</span><br><span class="line">            if (bluetoothSocket != null) &#123;</span><br><span class="line">              bluetoothSocket.close();</span><br><span class="line">              Log.v(Constants.HTTP_WZ, &quot;socket.close()&quot;);</span><br><span class="line">              bluetoothSocket = null;</span><br><span class="line">            &#125;</span><br><span class="line">            isRunning = false;</span><br><span class="line">          &#125; catch (Exception e2) &#123;</span><br><span class="line">            // TODO: handle exception</span><br><span class="line">          &#125;</span><br><span class="line">        &#125;</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;).start();</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  public BluetoothReceiver setBluetoothAdapter(BluetoothAdapter adapter) &#123;</span><br><span class="line">    this.bluetoothAdapter = adapter;</span><br><span class="line">    return this;</span><br><span class="line">  &#125;</span><br><span class="line">  </span><br><span class="line">  /**</span><br><span class="line">   * 反注册eventBus.</span><br><span class="line">   */</span><br><span class="line">  public void unRegister() &#123;</span><br><span class="line">    EventBus.getDefault().unregister(this);</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div>
<p>这个就是我的蓝牙广播类，这个逻辑又是怎么走的呢？</p>
<ol>
<li>前面服务里面注册的两个action，一个<strong><em>BluetoothDevice.ACTION_FOUND</em></strong>，还有一个<strong><em>BluetoothAdapter.ACTION_DISCOVERY_FINISHED</em></strong>，做了一个if判断，是发现了设备还是已经完成了扫描设备</li>
<li>发现设备之后，获取蓝牙信息，<strong>他这里是获取到一个蓝牙信息就会走一遍这个方法，并不是说一次获取一个列表</strong>。</li>
<li>找到了蓝牙设备之后就是连接了，伪代码讲解：</li>
</ol>
<div class="highlight-box"autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" contenteditable="true"data-rel="PLAIN"><figure class="iseeu highlight /plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br></pre></td><td class="code"><pre><span class="line">// 固定的UUID连接的时候需要uuid</span><br><span class="line">  private static final String SPP_UUID = &quot;00001101-0000-1000-8000-00805F9B34FB&quot;;</span><br><span class="line">  </span><br><span class="line">//获取socket</span><br><span class="line">BluetoothSocket bluetoothSocket =device.createRfcommSocketToServiceRecord(uuid);</span><br><span class="line"></span><br><span class="line">//连接之前取消扫描，注意非空判断。adapter是在服务里面申明的，通过setBluetoothAdapter方法传过来的</span><br><span class="line">bluetoothAdapter.cancelDiscovery();</span><br><span class="line"></span><br><span class="line">//连接，这里是阻塞的方式，注意要新开线程连接</span><br><span class="line">bluetoothSocket.connect();</span><br><span class="line"></span><br><span class="line">//获取输入流对象和输出流对象</span><br><span class="line">InputStream mInputStream = bluetoothSocket.getInputStream();</span><br><span class="line">OutputStream outputStream = bluetoothSocket.getOutputStream();</span><br><span class="line"></span><br><span class="line">//发送消息</span><br><span class="line">private void sendInstruct(String msg) &#123;</span><br><span class="line">    try &#123;</span><br><span class="line">      if (null == bluetoothSocket || !bluetoothSocket.isConnected()) &#123;</span><br><span class="line">        SocketUtils.reLinkBluetooth();</span><br><span class="line">        return;</span><br><span class="line">      &#125;</span><br><span class="line">      Log.v(Constants.HTTP_WZ, &quot;发送的数据--&gt;&quot; + msg + BluetoothInstruct.FINISH);</span><br><span class="line">      outputStream.write(msg.getBytes());</span><br><span class="line">      outputStream.flush();</span><br><span class="line">    &#125; catch (IOException e) &#123;</span><br><span class="line">      e.printStackTrace();</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">//接收消息，一次读一行，简单的蓝牙通信换行符作为结束标记</span><br><span class="line">BufferedReader br;</span><br><span class="line">while (isRunning) &#123;</span><br><span class="line">            br = new BufferedReader(new InputStreamReader(mInputStream, &quot;utf-8&quot;));</span><br><span class="line">            String s = br.readLine();</span><br><span class="line">            acceptReply(s);</span><br><span class="line">            Log.v(Constants.HTTP_WZ, &quot;收到的数据:&quot; + s);</span><br><span class="line">          &#125;</span><br><span class="line">          </span><br><span class="line">//异常的时候释放资源</span><br><span class="line">try &#123;</span><br><span class="line">            if (mInputStream != null) &#123;</span><br><span class="line">              mInputStream.close();</span><br><span class="line">              Log.v(Constants.HTTP_WZ, &quot;mInputSream.close()&quot;);</span><br><span class="line">            &#125;</span><br><span class="line">            if (outputStream != null) &#123;</span><br><span class="line">              outputStream.close();</span><br><span class="line">              Log.v(Constants.HTTP_WZ, &quot;outputStream.close()&quot;);</span><br><span class="line">            &#125;</span><br><span class="line">            if (bluetoothSocket != null) &#123;</span><br><span class="line">              bluetoothSocket.close();</span><br><span class="line">              Log.v(Constants.HTTP_WZ, &quot;socket.close()&quot;);</span><br><span class="line">              bluetoothSocket = null;</span><br><span class="line">            &#125;</span><br><span class="line">            isRunning = false;</span><br><span class="line">          &#125; catch (Exception e2) &#123;</span><br><span class="line">            // TODO: handle exception</span><br><span class="line">          &#125;</span><br></pre></td></tr></table></figure></div>
      
    </div>
    
      <footer class="article-footer">
        完
      </footer>
    
  </div>
  
    
<nav id="article-nav">
  <div class="article-nav-block">
    
      <a href="/2018/03/05/Android-WIFI功能——WifiManager/" id="article-nav-newer" class="article-nav-link-wrap">
        <strong class="article-nav-caption"></strong>
        <div class="article-nav-title">
          
            Android WIFI功能——WifiManager
          
        </div>
      </a>
    
  </div>
  <div class="article-nav-block">
    
      <a href="/2018/03/05/Android拍照功能——TakePhoto/" id="article-nav-older" class="article-nav-link-wrap">
        <div class="article-nav-title">Android拍照功能——TakePhoto</div>
        <strong class="article-nav-caption"></strong>
      </a>
    
  </div>
</nav>

    
  
  
</article>
</section>
        <aside id="sidebar">
  
    <div class="widget-box">
  <div class="avatar-box avatar-item">
    <img class="avatar" src="/uploads/artistic_image/head.jpg" title="头像来自网络"></img>
    <h3 class="avatar-name">
      
        海晨忆
      
    </h3>
    <p class="avatar-slogan">
      先谋生，再谋爱。人间值得，未来可期。
    </p>
  </div>
</div>


  
    
  <div class="widget-box">
    <h3 class="widget-title">分类</h3>
    <div class="widget">
      <ul class="category-list"><li class="category-list-item"><a class="category-list-link" href="/categories/Android-Socket/">Android -Socket</a></li><li class="category-list-item"><a class="category-list-link" href="/categories/Android-加密算法/">Android -加密算法</a></li><li class="category-list-item"><a class="category-list-link" href="/categories/Android-常用功能/">Android -常用功能</a></li><li class="category-list-item"><a class="category-list-link" href="/categories/Android-框架/">Android -框架</a></li><li class="category-list-item"><a class="category-list-link" href="/categories/Android-源码解析/">Android -源码解析</a></li><li class="category-list-item"><a class="category-list-link" href="/categories/Android-自定义view/">Android -自定义view</a></li><li class="category-list-item"><a class="category-list-link" href="/categories/Android-设计模式/">Android -设计模式</a></li><li class="category-list-item"><a class="category-list-link" href="/categories/JAVA-并发/">JAVA -并发</a></li><li class="category-list-item"><a class="category-list-link" href="/categories/Java-SpringBoot/">Java -SpringBoot</a></li><li class="category-list-item"><a class="category-list-link" href="/categories/Tomcat/">Tomcat</a></li><li class="category-list-item"><a class="category-list-link" href="/categories/kotlin/">kotlin</a></li><li class="category-list-item"><a class="category-list-link" href="/categories/数据库-JDBC/">数据库 -JDBC</a></li><li class="category-list-item"><a class="category-list-link" href="/categories/数据库-MySQL/">数据库 -MySQL</a></li></ul>
    </div>
  </div>


  
    

  
    
  
    
  <div class="widget-box">
    <h3 class="widget-title">归档</h3>
    <div class="widget">
      <ul class="archive-list"><li class="archive-list-item"><a class="archive-list-link" href="/archives/2021/07/">July 2021</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2019/11/">November 2019</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2019/10/">October 2019</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2019/09/">September 2019</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2019/08/">August 2019</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2019/07/">July 2019</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2019/06/">June 2019</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2018/10/">October 2018</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2018/05/">May 2018</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2018/03/">March 2018</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2018/02/">February 2018</a></li></ul>
    </div>
  </div>

  
    
  <div class="widget-box">
    <h3 class="widget-title">最新文章</h3>
    <div class="widget">
      <ul>
        
          <li>
            <a href="/2021/07/27/JAVA—公平锁，非公平锁，悲观锁，乐观锁，死锁/">JAVA—公平锁，非公平锁，悲观锁，乐观锁，死锁</a>
          </li>
        
          <li>
            <a href="/2021/07/19/JAVA—线程同步器AQS/">JAVA—线程同步器AQS</a>
          </li>
        
          <li>
            <a href="/2021/07/07/Android模拟点击/">Android模拟点击</a>
          </li>
        
          <li>
            <a href="/2019/11/27/SpringBoot系列-消息-RabbitMQ-（二十）/">SpringBoot系列-消息(RabbitMQ)（二十）</a>
          </li>
        
          <li>
            <a href="/2019/11/13/SpringBoot系列-Docker（十九）/">SpringBoot系列-Docker（十九）</a>
          </li>
        
      </ul>
    </div>
  </div>

  
      <div class="widget-box">
    <h3 class="widget-title">友情链接</h3>
    <div class="widget">
      
        <a class="hrf" style="display: block;" href="https://github.com/haichenyi" title target='_blank'
        >Github</a>
      
        <a class="hrf" style="display: block;" href="https://www.jianshu.com/u/6077ee440c37" title target='_blank'
        >简书</a>
      
        <a class="hrf" style="display: block;" href="https://blog.csdn.net/qq_27634797" title target='_blank'
        >CSDN</a>
      
    </div>
  </div>

  
</aside>
      </div>
      <footer id="footer">
  <div class="foot-box footers global-width">
    &copy;2017-2021 海晨忆 &nbsp;&nbsp;
    <script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    <span id="busuanzi_container_site_pv">阁下是第<span id="busuanzi_value_site_pv"></span>个访客</span>
  </div>
</footer>
      <script src="https://code.jquery.com/jquery-2.0.3.min.js"></script>
<script>
if (!window.jQuery) {
var script = document.createElement('script');
script.src = "/js/jquery-2.0.3.min.js";
document.body.write(script);
}
</script>

  <link rel="stylesheet" href="/fancybox/jquery.fancybox.css">
  <script src="/fancybox/jquery.fancybox.pack.js"></script>


<script src="/js/script.js"></script>



    </div>
    <nav id="mobile-nav" class="mobile-nav-box">
  <div class="mobile-nav-img mobile-nav-top"></div>
  
    <a href="/" class="mobile-nav-link">首页</a>
  
    <a href="/archives" class="mobile-nav-link">归档</a>
  
    <a href="/about" class="mobile-nav-link">简历</a>
  
  <div class="mobile-nav-img  mobile-nav-bottom"></div>
</nav>    
  </div>
</body>
</html>